package cn.com.eado.uwallpaper.net;

import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;

import cn.com.eado.uwallpaper.MyApplication;
import cn.com.eado.uwallpaper.utils.TUtil;

/**
 * Created by lcy on 2015/11/25.
 */
public class OkhttpRequest {
    public OkHttpClient mOkHttpClient;
    private static OkhttpRequest mInstance;

    public File getmFile() {
        return mFile;
    }

    private File mFile;
    private static final int FINISHDOWN = 4;
    private static final int DOWNERROR = 5;
    private static final int UPDATEPROGRESS = 7;

    //私有化构造器；
    private OkhttpRequest() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setCookieHandler(new CookieManager(new PersistentCookieStore(MyApplication.getContext()), CookiePolicy.ACCEPT_ALL));
    }

    //返回单例；
    public static OkhttpRequest getInstance() {
        if (mInstance == null) {
            synchronized (OkhttpRequest.class) {
                if (mInstance == null) {
                    mInstance = new OkhttpRequest();
                }
            }
        }
        return mInstance;
    }

    /**
     * 带有dialog的get请求；
     *
     * @param url
     * @param dialog
     * @param callback
     */
    public void getRequest(String url, ProgressDialog dialog, MyCallBack callback) {
        dialog.show();
//创建一个Request
        TUtil.showL("工具类里url=" + url);
        Request request = new Request.Builder()
                .url(url)
                .build();
//请求加入调度
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 带有dialog的post请求；
     *
     * @param url
     * @param body
     * @param dialog
     * @param callback
     */
    public void postRequest(String url, RequestBody body, ProgressDialog dialog, MyCallBack callback) {
        dialog.show();
        TUtil.showL("工具类里url=" + url);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 不带dialog的get请求；
     *
     * @param url
     * @param callback
     */
    public void getRequest(String url, Callback callback) {
//创建一个Request
        Request request = new Request.Builder()
                .url(url)
                .build();
//请求加入调度
        Log.e("LCY", "请求工具类的header=" + request.headers());
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 不带dialog的post请求；
     *
     * @param url
     * @param body
     * @param callback
     */
    public void postRequest(String url, RequestBody body, Callback callback) {
        TUtil.showL("工具类里url=" + url);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }


    /**
     * 下载文件；
     *
     * @param downloadUrl
     * @param destFileDir
     * @param destFileName
     * @param handler
     */
    public void downLoad(final String downloadUrl, final String destFileDir, final String destFileName, final Handler handler) {
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        TUtil.showL("路径=" + destFileDir + "name=" + destFileName);
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (!response.isSuccessful()) {
//                    throw new IOException("Unexpected code " + response);
                    handler.sendEmptyMessage(DOWNERROR);
                    return;
                }
                final long total = response.body().contentLength();
                long sum = 0;
                TUtil.showL("总长度="+total);
                File dir = new File(destFileDir) ;
                if (!dir.exists()) {
                    dir.mkdirs() ;
                }
                String newFilename = downloadUrl.substring(downloadUrl .lastIndexOf("/")+ 1);
                newFilename = destFileDir + newFilename;
                TUtil.showL ("文件名==" +newFilename);
                File file = new File(newFilename);
                //如果目标文件已经存在，则删除，产生覆盖旧文件的效果（此处以后可以扩展为已经存在图片不再重新下载功能）
                if (file.exists()) {
                    file.delete();
                }
                try {
                    //输入流
                    InputStream is = response.body().byteStream();
                    //1K的数据缓冲
                    byte[] bs = new byte[2048];
                    //读取到的数据长度
                    int len;
                    //输出的文件流
                    OutputStream os = new FileOutputStream(newFilename);
                    //开始读取
                    while ((len = is.read(bs)) != -1) {
                        sum += len;
                        os.write(bs, 0, len);
                        Message message=new Message();
                        message.obj=(int)(sum*100/total);
                        message.what=UPDATEPROGRESS;
                        handler.sendMessage(message);
                        TUtil.showL("当前进度=="+(1.0*sum/total)*100+"%");
                    }
                    //完毕，关闭所有链接
                    os.close();
                    is.close();
                    TUtil.showL("下载完毕..");
                    Message message=new Message();
                    message.obj=newFilename;
                    message.what=FINISHDOWN;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
